import { createApp } from "vue";

import "./style.css";
import App from "./App.vue";
import router from "@router/index";
import store from "@store/index";
import { INIT_ISAUTHENTICATED } from "@store/constant";

// 全局前置守卫
router.beforeEach(async (to, from) => {
  if (!to.meta.unRequiresAuth) {
    console.log("需要登陆检查...");
  }

  // 回到登陆页清空token
  if (to.name === "Login") {
    store.commit(INIT_ISAUTHENTICATED);
  }

  // 登陆状态
  const isAuthenticated = !!sessionStorage.getItem("my-app-token");
  // 检查用户是否已登录
  if (!to.meta.unRequiresAuth && !isAuthenticated) {
    console.log("非登陆用户，重定向到登陆页");

    // 将用户重定向到登录页面
    // return { name: 'Login' }
    return {
      path: "/login",
      // 保存前置的路由，方便登陆后直接重定向
      query: {
        redirectUrl: to.fullPath ? encodeURIComponent(to.fullPath) : "",
      },
    };
  }
});

createApp(App).use(router).use(store).mount("#app");
